// accounting/cashier_account_update/cashier_account_update.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableName: '新建账户',

    fieldList: [
      {field_id: 'account', label: '账户名称',type: 'text',is_null: false}
      ,{field_id: 'account_shortname', label: '账户简称',type: 'text',is_null: false}
      ,{field_id: 'currency_id', label: '币别',type: 'picklist',is_null: true, optionList: [],optionId: 'id',optionName: 'name'}
      ,{field_id: 'bankNo', label: '银行账号',type: 'text',is_null: true}
    ],
    formData: {
      account: '',
      account_shortname: '',
      currency_id: '',
      bankNo: '',
      number:''
    },

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项
  },

  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //布局中字段修改
  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val,
      formData = this.data.formData;
    formData[id] = val;
  },

  //绑定提交
  bindSubmit(e){
    let type = e.currentTarget.dataset.type;

    // 开启验证
    this.data.validObj = {};
    this.setData({
      validFlag: !this.data.validFlag,
    });
    let {validObj} = this.data;
    this.validForm(validObj).then(valid => {
      if(valid) { // 表单验证通过
        let {formData,tableName} = this.data;
        console.log('表单验证通过');
        let url = 'CashierAccount/create_all_cashier_account';
        if (formData.number){
          url = 'CashierAccount/alter_all_cashier_account';
        }
        wx.$post(3,url,formData).then(res=>{
          if (res.errcode !=0)return;
          wx.$toast('保存成功！');
          this.refreshList(formData.number,this.data.editIndex)

          //关闭
          if (type === 'close'){
            wx.navigateBack({ //跳转到前一个页面
              delta:1,//前一个页面
            });
          }
          //清空
          if (type === 'clear'){

            const pages = getCurrentPages();//获取页面栈
            const beforePage = pages[pages.length - 2];  //前一个页面
            if (!beforePage.data.auth.tableAppend) {
              wx.$toast('抱歉，您没有权限新增该模块数据！');
              wx.navigateBack({ //跳转到前一个页面
                delta:1,//前一个页面
              });
              return
            }

            formData = {};
            tableName = '新增账户';
          }
          this.setData({
            formData,
            tableName
          });
        });

      } else {  // 表单验证不通过
        console.log('表单验证不通过');
        wx.$toast('必填项不能为空！')
      }
    })
  },

  //刷新列表
  refreshList(id,index){
    const pages = getCurrentPages();//获取页面栈
    const beforePage = pages[pages.length - 2];  //前一个页面
    beforePage.refreshData(id,index);
  },

  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },

  getData(rid){
    return new Promise(resolve => {
      wx.$post(3,'CashierAccount/query_all_cashier_account',{"limit":0,"page":1,"oby":"account_id","SearchWhere":[{"CompareWith":"number","Operator":"=","CompareValue": rid,"or":0}]}).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        resolve(data);
      })
    })
  },
  /*获取币别*/
  getCurrency() {
    return new Promise(resolve => {
      wx.$get(3,'CashierAccount/select_all_currency').then(res=>{
        resolve();
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        this.setData({
          [`fieldList[2].optionList`]: data
        })
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    await this.getCurrency();
    let {number,edit_index} = options,
      tableName = '新增账户',
      obj = {};
    if (number){
      tableName = '编辑账户'
    }
    obj = {tableName};
    if (edit_index !== undefined)obj.editIndex = edit_index;
    this.setData(obj);
    if (number){
      this.getData(number).then(row=>{
        let data= row[0],
          {formData} = this.data;
        wx.$each(formData,(key,val)=>{
          formData[key] = data[key];
        });
        this.setData({formData})

      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
